package com.upsuns.transfer;

import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *@Description:<p>文件接收终端</p>
 *@author 王旭
 *@time 2016-1-30 下午5:49:33
 */
public class ServerTerminal implements Terminal {
	
	private int port; //监听端口
	
	private ServerSocket server;
	
	
	public ServerTerminal(int port) {
		this.port = port;
		try {
			server = new ServerSocket(port);
		} catch (IOException e) {
			System.out.println("创建服务失败");
			e.printStackTrace();
		}
	}


	@Override
	public void receive(RandomAccessFile raf, long start, long len) throws IOException {
		byte buffer[] = new byte[1024]; //接收数据缓冲区
		
		raf.seek(start); //定位文件指针
		
		Socket socket = server.accept(); //接收服务端请求，获取socket
		
		InputStream in = socket.getInputStream(); //获取输入流
		
		//写入数据
		int l = 0; 
		while((l = in.read(buffer)) != -1) {
			raf.write(buffer, 0, l);
			start += l;
			raf.seek(start);
		}
		
		in.close();
		
	}


	@Override
	public void send(RandomAccessFile raf, long start, long len) {
		
	}


	public int getPort() {
		return port;
	}


	public void setPort(int port) {
		this.port = port;
	}

}
